using WorkflowCore.Interface;
using WorkflowCore.Persistence.SqlServer;
using WorkflowCore.Models;
using SqlSugar;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddOpenApi();

// Add CORS for frontend integration
builder.Services.AddCors(options =>
{
    options.AddPolicy("AllowAll", policy =>
    {
        policy.AllowAnyOrigin()
              .AllowAnyMethod()
              .AllowAnyHeader();
    });
});

// Add WorkflowCore services with enhanced configuration
builder.Services.AddWorkflow(cfg =>
{
    var connectionString = builder.Configuration.GetConnectionString("WorkflowDb");
    cfg.UseSqlServer(connectionString, true, true);
    
    // 配置工作流引擎参数
    cfg.MaxConcurrentItems = builder.Configuration.GetValue<int>("WorkflowCore:MaxConcurrentItems", 10);
    cfg.IdleTime = TimeSpan.Parse(builder.Configuration.GetValue<string>("WorkflowCore:IdleTime", "00:00:30"));
    cfg.RetryInterval = TimeSpan.Parse(builder.Configuration.GetValue<string>("WorkflowCore:RetryInterval", "00:00:05"));
});

// 配置SqlSugar
builder.Services.AddSingleton<ISqlSugarClient>(sp =>
{
    return new SqlSugarClient(new ConnectionConfig
    {
        ConnectionString = builder.Configuration.GetConnectionString("WorkflowDb"),
        DbType = DbType.SqlServer,
        IsAutoCloseConnection = true,
        InitKeyType = InitKeyType.Attribute
    });
});

var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.MapOpenApi();
}

app.UseHttpsRedirection();
app.UseCors("AllowAll");

// 启动工作流引擎
var workflowHost = app.Services.GetService<IWorkflowHost>();
workflowHost?.Start();

app.MapControllers();

app.Run();

record WeatherForecast(DateOnly Date, int TemperatureC, string? Summary)
{
    public int TemperatureF => 32 + (int)(TemperatureC / 0.5556);
}
